function ListNode(val, next) {
  this.val = (val===undefined ? 0 : val)
  this.next = (next===undefined ? null : next)
}
function createList(arr) {
  if(arr.length == 0)
    return null;
  let head = new ListNode(arr[0], null), headNode = head;
  for(let i = 1; i < arr.length; i++) {
    let temp = new ListNode(arr[i], null);
    head.next = temp;
    head = temp;
  }
  return headNode;
}
function showList(head) {
  while(head) {
    console.log(head.val);
    head = head.next;
  }
}

/**
 * @param {ListNode} head
 * @param {number} val
 * @return {ListNode}
 */
var removeElements = function(head, val) {
  head = createList(head);
  // showList(head);
  let temp = head;
  while(head && head.val == val) {
    temp = head;
    head = head.next;
    delete temp;
  }
  if(!head) return null;
  temp = head.next, last = head;
  while(temp) {
    if(temp.val == val) {
      let node = temp;
      temp = temp.next;
      last.next = temp;
      delete node;
      continue;
    }
    last = temp;
    temp = temp.next;
  }
  return head;
  showList(head);
};
let head = [1,2,6,3,4,5,6], val = 6;
console.log(removeElements(head, val));
head = [], val = 1;
console.log(removeElements(head, val));
head = [7, 7, 7, 7], val = 7;
console.log(removeElements(head, val));
head = [1,2,2,1], val = 2;
console.log(removeElements(head, val));
